package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetMealService;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/report")
public class ReportController {

   @Autowired
    private ReportService reportService;
   @Autowired
    private MemberService memberService;
   @Autowired
    private SetMealService setMealService;

    /**
     *         "reportDate": "2022-06-02",   报表的日期
     * 会员数据统计
     *         "todayNewMember": 0,    今日新增会员数
     *                 "thisWeekNewMember": 0,  本周新增会员
     *         "thisMonthNewMember": 0,  本月新增会员数
     *                  "totalMember": 7,    总会员数
     * 预约到诊数据统计
     *         "todayVisitsNumber": 0,    今日预约数
     *                  "todayOrderNumber": 0,   今日到诊数
     *         "thisWeekVisitsNumber": 0, 本周预约数
     *                  "thisWeekOrderNumber": 0  本周到诊数
     *         "thisMonthOrderNumber": 0, 本月到到诊数
     *         "thisMonthVisitsNumber": 0, 本月预约数
     * 热门套餐预约数据数量
     *               hotSetmeal ：0        热门套餐的数据统计
     *运营数据统计
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try{
            //获取会员数据的信息进行统计.
            //获取预约到诊数据的信息进行统计
            //获取预约套餐的数据进行统计
            //调用业务层获取数据,创建一个集合用来封装数据
            Map<String,Object> reportMap = reportService.listReportData();
            log.info("[统计分析-运营数据统计],reportMap:{}",reportMap);
            return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS,reportMap);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConst.GET_BUSINESS_REPORT_FAIL);
        }

    }
    /**
     * 查询用户报告
     *
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {

        List<String> months = new ArrayList<>();
        List<Integer> memeberCount = null;
        //构造months
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-12);
        DateFormat df = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i <12 ; i++) {
            months.add(df.format(cal.getTime()));
            cal.add(Calendar.MONTH,1);
        }

        //构造memberCount
        memeberCount = memberService.countByMonth(months);

        Map<String,Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memeberCount);
        return  new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }



    /**
     * 导出运营数据报表
     *
     * @return
     */
    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        log.info("[导出运营数据报表]开始");
        //1-RPC获取数据
        Map<String, Object> reportData = reportService.listReportData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);
        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Integer totalMember = (Integer) reportData.get("totalMember");
        // 获取预约相关数据
        Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
        Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
        Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
        Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
        Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");

        //2-读取模板构造workBook
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             XSSFWorkbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);
            return null;
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
       //套餐预约占比饼形图
        @RequestMapping("/getSetmealReport")
        public  Result  getSetmealReport(){
            Map<String,Object> data = new HashMap<>();

            try{
                List<Map<String, Object>> setmealCount=setMealService.findSetmealCount();
                data.put("setmealCount",setmealCount);
                List<String> setmealNames=new ArrayList<>();
                for (Map<String, Object>  map : setmealCount) {
                    String name = (String) map.get("name");
                    setmealNames.add(name);
                }

                data.put("setmealNames",setmealNames);
                return new Result(true,MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConst.GET_SETMEAL_COUNT_REPORT_FAIL);

            }

        }
}
